import {queryCount, queryDetail} from "../services/poet";

export default {

  namespace: 'detail',

  state: {
    preVisible: false,
    preImgUrl: null,
    toastType: 0,
    // pic: 'https://s3.mogucdn.com/mlcdn/c45406/180404_5fi9b1l2c3b0bg71ddcj66dd4abbg_1280x854.jpg',
    title: '菩萨蛮',
    author: '刘学箕',
    accessCount: {
      total: 1,
      count: 1,
    },
    content: '昨日杏花春满树。\n' +
    '今晨雨过香填路。\n' +
    '零落软胭脂。\n' +
    '湿红无力飞。\n' +
    '转头春易去。\n' +
    '春色归何处。\n' +
    '待密与春期。\n' +
    '春归人也归。',
    explain: null,
    cardTitle: "诗词", // 详情页诗词标题，默认是根据 朝代 + 诗词类型组成，如 唐诗 | 七绝
  },

  subscriptions: {
    setup({dispatch, history}) {  // eslint-disable-line
      // dispatch({
      //   type: 'pageCount',
      // })
    },

    watchAndRefreshList({dispatch, history}) {
      // console.log("刷新了？");
      // let reg = new RegExp("(^|[&?])pid=([^&]*)(&|$)");
      // const pid = history.location.search.match(reg)[2];
      // dispatch({
      //   type: 'fetch',
      //   payload: pid,
      // })
    },
  },

  effects: {
    // 启动时，主动拉取最新的数据
    * pageCount({payload}, {call, put}) {  // eslint-disable-line
      const countRes = yield call(queryCount);
      if (countRes.data.status && countRes.data.status.code === 200) {
        yield put({type: 'updateCount', payload: countRes.data.result});
      }
    },

    // 查询诗词详情
    * fetch({payload}, {call, put}) {
      const res = yield call(queryDetail, payload);
      yield put({
        type: 'loadDetail',
        payload: res.data.result,
      });
    },

    * hideOrShowToast({payload}, {put}) {
      yield put({
        type: 'operateToast',
        payload: payload,
      })
    },

    * updatePreUrl({payload}, {put}) {
      yield put({
        type: 'save',
        payload: payload,
      })
    },

    * hideOrShowPre({payload}, {call, put}) {
      yield put({
        type: 'operatePre',
        payload: payload,
      })
    },
  },

  reducers: {
    updateCount(state, {payload: apps}) {
      return {...state, apps, accessCount: apps};
    },

    loadDetail(state, {payload: apps}) {
      return {
        ...state, apps,
        title: apps.title,
        author: apps.author,
        content: apps.content,
        explain: apps.explain,
        cardTitle: apps.dynasty + " | " + apps.theme,
      }
    },

    // 图片生成成功，更新toast状态，显示提示信息，并在新的标签上显示生成的图片
    save(state, {payload: apps}) {
      return {...state, apps, preImgUrl: apps, preVisible: true, toastType: 1};
    },

    // 图片生成失败，更新toast，显示失败的提示信息
    operateToast(state, {payload: apps}) {
      return {...state, apps, toastType: apps};
    },

    operatePre(state, {payload: apps}) {
      return {...state, apps, preVisible: apps}
    }
  },

};
